package com.levi.completableFuture;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author shentong
 * @since 2022/1/16 8:27 PM
 * anyOf()方法用于对多个异步任务的结果进行操作，获取最先执行玩的那个任务的结果
 */
public class AnyOfDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println("第一个任务执行完");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 1;
        }, executorService);
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println("第二个任务执行完");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 2;
        }, executorService);
        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
                System.out.println("第三个任务执行完");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 3;
        }, executorService);
        List<CompletableFuture<Integer>> list = new ArrayList<>();
        list.add(future1);
        list.add(future2);
        list.add(future3);
        CompletableFuture<Object> future = CompletableFuture.anyOf(list.toArray(new CompletableFuture[]{}));
        future.thenRunAsync(()->{
            try {
                Integer value = (Integer) future.get();
                System.out.println("最先获取的结果是:>>>"+value);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            executorService.shutdown();
        },executorService);
        System.out.println("Main end~~");
    }
}
